<!-- SPC曲线 交接班 -->
<template>
  <div class="app-container" style="padding: 0">
    <px-form ref="queryRef" class="custom-form-ui" :model="queryParams" :inline="true" label-width="90px">
      <px-form-item label="科室">
        <px-select v-model="queryParams.classCode" placeholder="请选择科室" clearable style="width: 210px" filterable @change="setreceiveCompanyCode">
          <px-option v-for="dict in liquidList" :key="dict.id" :label="dict.itemName" :value="dict.itemValue" />
        </px-select>
      </px-form-item>
      <px-form-item label="系统">
        <px-tree-select
          v-model="queryParams.systemCode"
          clearable
          style="width: 100%"
          placeholder="请选择设备系统（树状图）"
          :props="defaultProps"
          :data="systemList"
          check-strictly
          multiple
          :render-after-expand="false"
          collapse-tags
          collapse-tags-tooltip
        />
      </px-form-item>
      <px-form-item label="指标名称">
        <px-input v-model="queryParams.indicatorName" placeholder="请输入指标名称" style="width: 210px" clearable />
      </px-form-item>
      <px-form-item label="指标级别">
        <px-select v-model="queryParams.indicatorLevel" placeholder="请选择接指标级别" clearable style="width: 240px" filterable>
          <px-option v-for="dict in receiveCompanyList" :key="dict.id" :label="dict.itemName" :value="dict.itemValue" />
        </px-select>
      </px-form-item>
      <px-form-item label="时间日期" style="width: 430px !important">
        <px-date-picker
          v-model="dateRange"
          type="datetimerange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          :default-time="defaultTime"
        />
      </px-form-item>
      <px-button style="margin-top: -17px" type="primary" icon="" @click="handleQuery('search')">搜索</px-button>
      <px-button style="margin-top: -17px" icon="" @click="resetQuery">重置</px-button>
    </px-form>
    <div class="spcchart">
      <unfoldChrats :SpcAnalysis="spcAnalysis" />
    </div>
  </div>
</template>

<script setup name="Dict" lang="ts">
// import useDictStore from '@/store/modules/dict'
defineOptions({
  name: "SystemDataDict"
});
// import { router } from "@/router";
import { useRoute } from "vue-router";
import { PxMessage, PxMessageBox } from "px-ui";
import { getCurrentInstance, ref, toRefs, reactive, onMounted } from "vue";
import { getToken } from "@/utils/auth";
import { queryChildByTypeCodeAndItemValue } from "@/api/waterClass";
import { spcqueryList, spcquerySpcAnalysis, spcIndicatorquerySpcAnalysisResultList, twinPointpageTwinPoint } from "@/api/spc";
import { querySystemSelect } from "@/api/equip/archive";
import unfoldChrats from "../components/unfoldChrats.vue";

const route = useRoute();
const { proxy }: any = getCurrentInstance();
const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 1), new Date(2000, 1, 1, 23, 59, 59)];

const defaultProps = {
  children: "children",
  label: "name",
  value: "code"
};
// 如果有厂区和科室，根据他们的值获取系统
const handleSystemFocus = async () => {
  systemList.value = await querySystemSelect({ factoryArea: "", className: queryParams.value.classCode });
};

const setreceiveCompanyCode = val => {
  let setvalue = null;
  setvalue = liquidList.value.find(option => option.itemValue == val);
  if (setvalue && setvalue?.itemDesc != "") {
    queryParams.value.receiveCompanyCode = JSON.parse(setvalue.itemDesc).receiveCompanyCode;
  } else {
    queryParams.value.receiveCompanyCode = "";
  }
  handleSystemFocus();
};

onMounted(() => {
  loading.value = true;
  queryCategoryList();
  getList();
  handleSystemFocus();
});

const typeList = ref([]);
const loading = ref(true);
const dateRange = ref([]);
const data = reactive({
  systemList: [],
  liquidList: [],
  receiveCompanyList: [],
  queryParams: {
    indicatorName: "",
    classCode: route.query.className ? route.query.className.toUpperCase() : "",
    systemCode: [],
    indicatorLevel: "",
    startTime: "",
    endTime: "",
    querySpcCount: true,
    pageNum: 1,
    pageSize: 20
  },
  headers: {
    Authorization: "Bearer " + getToken().accessToken || ""
  }
});

const { liquidList, receiveCompanyList, queryParams, systemList } = toRefs(data);
// 获取查询到的所有jobIds
const jobIdsList = ref([]);
const spcAnalysis = ref([]);

const queryCategoryList = () => {
  queryChildByTypeCodeAndItemValue({
    typeCode: "className"
  }).then((response: any) => {
    liquidList.value = response;
  });
  queryChildByTypeCodeAndItemValue({
    typeCode: "SPCL"
  }).then((response: any) => {
    receiveCompanyList.value = response;
  });
  const end = new Date();
  end.setHours(23, 59, 59, 0);
  end.setTime(end.getTime());
  const start = new Date();
  start.setHours(0, 0, 0, 0);
  start.setTime(start.getTime());
  dateRange.value = [formatDate(start), formatDate(end)];
};
const handleSpcAnalysis = jobIds => {
  if (jobIds && jobIds.length) {
    spcquerySpcAnalysis({
      jobIdList: jobIds,
      timePeriod: "minutes", //先给个默认值
      startTime: queryParams.value.startTime,
      endTime: queryParams.value.endTime
    }).then((response: any) => {
      spcAnalysis.value = response;
    });
  } else {
    spcAnalysis.value = [];
  }
};
function getList() {
  loading.value = true;

  if (dateRange.value != null) {
    queryParams.value.startTime = dateRange.value[0];
    queryParams.value.endTime = dateRange.value[1];
  } else {
    queryParams.value.startTime = "";
    queryParams.value.endTime = "";
  }
  spcqueryList(queryParams.value).then((response: any) => {
    jobIdsList.value = [];
    if (response.data) {
      jobIdsList.value = response.data.map(v => v.jobId);
    }
    handleSpcAnalysis(jobIdsList.value);
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery(type) {
  if (type == "search") {
    queryParams.value.pageNum = 1;
  }
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    indicatorName: "",
    classCode: route.query.className ? route.query.className.toUpperCase() : "",
    systemCode: [],
    indicatorLevel: "",
    startTime: "",
    endTime: "",
    querySpcCount: true
  };
  const end = new Date();
  end.setHours(23, 59, 59, 0);
  end.setTime(end.getTime());
  const start = new Date();
  start.setHours(0, 0, 0, 0);
  start.setTime(start.getTime());
  dateRange.value = [formatDate(start), formatDate(end)];
  handleQuery("reset");
}

function formatDate(date) {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const h = date.getHours().toString().padStart(2, "0");
  const m = date.getMinutes().toString().padStart(2, "0");
  const s = date.getSeconds().toString().padStart(2, "0");
  return `${year}-${month}-${day} ${h}:${m}:${s}`;
}
</script>
<style scoped lang="scss">
.app-container {
  margin-top: 20px;
  background: none;
}

.spcchart {
  width: 100%;
  margin-top: 20px;
}
</style>
